<script setup lang="ts">
import { computed, ref } from 'vue'
import {useRouter} from 'vue-router'
import {MessagePlugin} from 'tdesign-vue-next'
import TaskTabs from './components/TaskTabs.vue'
import KeywordList from './components/KeywordList.vue'

import { mockMessageList, type Message, user, robot } from './config/index'
import { KEY_WORDSLIST } from './config/constant'
import {useUserStore} from '@/store'
import {createChat} from '@/api/chat'
import { openLogin } from '@/components/login/index';

const router=useRouter();
const warnMsg=ref('')
//document.title = 'AI对话'
const robotRuning=ref(false)
const userStore=useUserStore()
const containerRef = ref<HTMLDivElement | null>(null)
const inputRef = ref<HTMLInputElement>()
const inputValue = ref('')
const messgeList = ref<Array<Message>>(mockMessageList)
const init = () => {
  const dom = containerRef.value as HTMLDivElement
  if (dom) {
    setTimeout(() => {
      dom.scrollTo(0, dom.scrollHeight )
    }, 0)
  }
}

const userSpeak = (item: string) => {
  const userMsg: Message = {
    id: userStore.userInfo.user_id,//uuidv4(),
    type: 'user',
    msg: {
      text: item
    }
  }
  messgeList.value.push(userMsg)
  robotSpeak(item)
}

const robotSpeak = (item: string) => {
  robotRuning.value=true
  let mesInfo:Message= {
    id: '1',
    type: 'robot',
    msg: {
      text: '正在处理中......'
    }
  }
  messgeList.value.push(mesInfo)

  if(item==='人工客服')
  {
    messgeList.value.splice(messgeList.value.length-2)
    let mesInfo:Message= {
      id: '1',
      type: 'robot',
      msg: {
        text: '请使用微信扫码联系',
        imgUrl:'https://res.rscode.cn/kf.png?imageView2/2/w/220/h/220'
      }
    }
    messgeList.value.push(mesInfo)
    init()
    return;
  }
  if(item==='PDF转换')
  {
    messgeList.value.splice(messgeList.value.length-1)
    router.push('/doc/convert')
    let mesInfo:Message= {
      id: '1',
      type: 'robot',
      msg: {
        text: '己跳转至'+item,
      }
    }
    messgeList.value.push(mesInfo)
    init()
    return;
  }
  if(item==='AI绘画')
  {
    messgeList.value.splice(messgeList.value.length-1)
    router.push('/picture/drawing')
    let mesInfo:Message= {
      id: '1',
      type: 'robot',
      msg: {
        text: '己跳转至'+item,
      }
    }
    messgeList.value.push(mesInfo)
    return;
  }



  var msgs={
   content:item
   }
  createChat(msgs).then(ret=>{
    messgeList.value.splice(messgeList.value.length-1)
    let mesInfo:Message= {
      id: ret.id,
      type: 'robot',
      msg: {
        text: ret.result
      }
    }
    messgeList.value.push(mesInfo)
    init()
    warnMsg.value=''
  })
  .catch(e=>{
    console.log(JSON.stringify(e))
    let msg=e.message??e.msg
    let mesInfo:Message= {
      id: '1',
      type: 'robot',
      msg: {
        text: msg
      }
    }
    messgeList.value.push(mesInfo)
    warnMsg.value=msg
  })
  .finally(()=>{
    robotRuning.value=false
  })
}

const clickItem = (item: string) => {
  inputValue.value = ''
  userSpeak(item)
}

const sendMsg = () => {
  if(userStore.token&&userStore.token.length<10)
  {
     openLogin()
    return;
  }
  userSpeak(inputValue.value)
  inputValue.value = ''
  inputRef.value?.blur()
}

const onPressEnter = () => {
  sendMsg()
}

const keywordList = computed(() => {
  return KEY_WORDSLIST.filter((item) => item.includes(inputValue.value) && inputValue.value.trim())
})
</script>

<template>
  <div class="chat-view">
    <t-space v-if="warnMsg!=''" style="width: 100%">
        <t-alert theme="warning" :message="warnMsg" close>
        </t-alert>
      </t-space>
    <div class="chat-view__container" ref="containerRef">
      <template v-for="(item,index) in messgeList" :key="item.id">
        <!-- robot -->
        <div class="chat-view-robot" v-if="item.type === 'robot'">
          <div class="chat-view-robot__avatar">
            <img class="img" :src="robot.avatar" />
          </div>
          <div class="chat-view-robot__content">
            <div class="chat-view-robot__name">{{ robot.name }}</div>
            <!-- 机器消息 -->
            <div class="chat-view-robot__msgBox">
              <div class="chat-view-robot__message" v-if="item.msg.text || item.msg.imgUrl">
                <span v-if="index===messgeList.length-1" class="text">
                 <vuetyped :strings="[item.msg.text]" :loop="false" :smart-backspace="true">
                   <div class="typing"></div>
                 </vuetyped>
                </span>
                <span v-else  class="text">
                  {{ item.msg.text }}
                </span>
                <img class="img" :src="item.msg.imgUrl" alt="" />
              </div>
            </div>
            <!-- 机器人自定义模块 -->
            <div class="chat-view-robot__msgBox" v-if="item.compontent">
              <div class="chat-view-robot__component">
                <Component
                  @onClick="userSpeak"
                  :is="comp"
                  v-for="(comp, index) in item.compontent"
                  :key="index"
                />
              </div>
            </div>
          </div>
        </div>
        <!-- 用户 -->
        <div class="chat-view-user" v-if="item.type === 'user'">
          <div class="chat-view-user__content">
            <div class="chat-view-user__name">{{ user.name }}</div>
            <div class="chat-view-user__msgBox">
              <div class="chat-view-user__message">
                <span>{{ item.msg.text }}</span>
              </div>
            </div>
          </div>
          <div class="chat-view-user__avatar">
            <img class="img" :src="user.avatar" alt="" />
          </div>
        </div>
      </template>
    </div>
    <div class="chat-view-footer">
      <TaskTabs @clickTabs="userSpeak" />
      <div class="chat-view-footer__keyword" v-if="keywordList.length > 0">
        <KeywordList :list="keywordList" @clickItem="clickItem" :keyword="inputValue" />
      </div>
      <div class="chat-view-footer__inputBox">
        <input
          class="input"
          @keydown.enter="onPressEnter"
          placeholder="可随时向我提问"
          ref="inputRef"
          v-model="inputValue"
          enterkeyhint="send"
        />
        <t-button class="button" :disabled="inputValue.trim().length <= 0||robotRuning===true" @click="sendMsg">发送</t-button>
      </div>
    </div>
  </div>
</template>

<style lang="less">
@import './index.less';
</style>
